<template>
  <Page class="bg-[#f5f7fa] text-[#333] leading-[1.6] min-h-screen max-w-[750rpx] mx-auto px-[16rpx] relative">
    <view class="container w-full max-w-[480rpx] mx-auto pt-[40rpx]">
      <!-- 头部区域 -->
      <view class="header text-center mb-[50rpx]">
        <view class="logo w-[80rpx] h-[80rpx] bg-gradient-to-br from-[#2196F3] to-[#21CBF3] rounded-[20rpx] flex items-center justify-center mx-auto mb-[20rpx]">
          <IconFont name="icon-smartphone" class="text-[42rpx] text-white" />
        </view>
        <text class="block text-[28rpx] font-semibold text-[#333] mb-[10rpx]">手机号登录</text>
        <text class="text-[15rpx] text-[#999]">未注册用户将自动创建账号</text>
      </view>
      
      <!-- 表单区域 -->
      <view class="form-group mb-[25rpx] bg-white rounded-[12rpx] overflow-hidden shadow-[0_2rpx_10rpx_rgba(0,0,0,0.03)]">
        <view class="input-row flex items-center px-[16rpx] border-b border-[#eee]">
          <text class="prefix text-[16rpx] text-[#333] mr-[10rpx]">+86</text>
          <input 
            type="tel" 
            v-model="phone"
            class="flex-1 h-[56rpx] border-none outline-none text-[17rpx] py-[10rpx] bg-transparent"
            placeholder="请输入手机号" 
            maxlength="11"
            @input="validatePhone"
          >
        </view>
        <view class="input-row flex items-center px-[16rpx]">
          <input 
            type="text" 
            v-model="code"
            class="flex-1 h-[56rpx] border-none outline-none text-[17rpx] py-[10rpx] bg-transparent"
            placeholder="请输入验证码" 
            maxlength="6"
            @input="validateForm"
          >
          <nut-button 
            id="getCodeBtn" 
            class="get-code bg-[#2196F3] text-white border-none px-[16rpx] py-[8rpx] rounded-[20rpx] text-[14rpx] cursor-pointer transition-all duration-300"
            :disabled="!canGetCode || isCounting"
            @click="getVerificationCode"
          >
            <template v-if="!isCounting">获取验证码</template>
            <template v-if="isCounting">{{ countDown }}秒</template>
          </nut-button>
        </view>
      </view>
      
      <view 
        id="tip" 
        class="tip text-[13rpx] text-[#2196F3] px-[16rpx] py-[8rpx] bg-[rgba(33,150,243,0.1)] rounded-[8rpx] mt-[10rpx]"
        :class="{ 'hidden': !showTip }"
      >
        {{ tipText }}
      </view>
      
      <nut-button 
        id="loginBtn" 
        class="login-btn w-full bg-[#2196F3] text-white border-none rounded-[12rpx] py-[16rpx] text-[18rpx] font-medium mt-[30rpx] shadow-[0_4rpx_12rpx_rgba(33,150,243,0.3)] transition-all duration-300 active:translate-y-[2rpx] active:shadow-[0_2rpx_8rpx_rgba(33,150,243,0.3)]"
        :disabled="!canLogin"
        @click="handleLogin"
      >
        登录 / 注册
      </nut-button>
      
      <!-- 分割线 -->
      <view class="divider flex items-center justify-center mt-[30rpx] mb-[30rpx]">
        <view class="line flex-1 h-[1rpx] bg-[#eee]"></view>
        <text class="text-[14rpx] text-[#999] px-[20rpx]">或</text>
        <view class="line flex-1 h-[1rpx] bg-[#eee]"></view>
      </view>
      
      <!-- 微信授权登录按钮 -->
      <nut-button 
        id="wechatLoginBtn" 
        class="wechat-login-btn w-full bg-[#07C160] text-white border-none rounded-[12rpx] py-[16rpx] text-[18rpx] font-medium shadow-[0_4rpx_12rpx_rgba(7,193,96,0.3)] transition-all duration-300 active:translate-y-[2rpx] active:shadow-[0_2rpx_8rpx_rgba(7,193,96,0.3)] flex items-center justify-center"
        :disabled="isWechatLoading"
        @click="handleWechatLogin"
      >
        <IconFont name="icon-wechat" class="text-[20rpx] mr-[8rpx]" />
        <template v-if="!isWechatLoading">微信一键登录</template>
        <template v-if="isWechatLoading">授权中...</template>
      </nut-button>
      
      <view class="terms text-center mt-[30rpx] text-[13rpx] text-[#999]">
        登录即代表同意 
        <text class="text-[#2196F3]">用户协议</text> 
        和 
        <text class="text-[#2196F3]">隐私政策</text>
      </view>
    </view>
    
    <view class="footer absolute bottom-[20rpx] left-0 right-0 text-center text-[13rpx] text-[#999]">
      ©2023 智能开发平台 · 安全登录
    </view>
  </Page>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Taro } from '@tarojs/taro'
import { Button as nutButton } from '@nutui/nutui-taro'
import { IconFont } from '@nutui/icons-vue-taro'
import { wechatAuth } from '@/core/config'

// 表单数据
const phone = ref('')
const code = ref('')

// 状态管理
const isCounting = ref(false)
const countDown = ref(60)
const showTip = ref(true)
const tipText = ref('提示：未注册的手机号将自动注册并登录')
const isWechatLoading = ref(false)

// 验证相关
const canGetCode = computed(() => {
  // 手机号正则：11位数字，以1开头
  return /^1[3-9]\d{9}$/.test(phone.value)
})

const canLogin = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value) && /^\d{6}$/.test(code.value)
})

/**
 * 验证手机号
 * @description 验证手机号格式并显示相应提示
 */
const validatePhone = () => {
  if (phone.value.length === 0) {
    showTip.value = false
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    showTip.value = true
    tipText.value = '请输入正确的手机号码'
  } else {
    showTip.value = true
    tipText.value = '提示：未注册的手机号将自动注册并登录'
  }
}

/**
 * 验证表单
 * @description 触发计算属性更新
 */
const validateForm = () => {
  // 自动触发计算属性更新
}

/**
 * 获取验证码
 * @description 发送短信验证码并开始倒计时
 */
const getVerificationCode = () => {
  if (!canGetCode.value) return
  
  // 模拟发送验证码
  Taro.showToast({
    title: `验证码已发送至 ${phone.value}`,
    icon: 'none',
    duration: 2000
  })
  
  // 开始倒计时
  isCounting.value = true
  let count = 60
  const timer = setInterval(() => {
    count--
    countDown.value = count
    if (count <= 0) {
      clearInterval(timer)
      isCounting.value = false
      countDown.value = 60
    }
  }, 1000)
  
  // 实际应用中这里应该调用后端API发送验证码
  console.log(`发送验证码到: ${phone.value}`)
  
  // 测试用：自动填充验证码
  setTimeout(() => {
    code.value = '123456'
  }, 1000)
}

/**
 * 登录/注册处理
 * @description 处理手机号验证码登录
 */
const handleLogin = () => {
  if (!canLogin.value) return
  
  // 显示登录中提示
  showTip.value = true
  tipText.value = '登录中，请稍候...'
  
  // 模拟登录请求
  setTimeout(() => {
    Taro.showToast({
      title: `登录成功！欢迎 ${phone.value}`,
      icon: 'none',
      duration: 2000
    })
    
    // 实际应用中这里应该跳转到首页
    console.log(`登录成功: ${phone.value}`)
  }, 1500)
}

/**
 * 微信授权登录
 * @description 处理微信授权登录流程
 */
const handleWechatLogin = async () => {
  if (isWechatLoading.value) return
  
  try {
    isWechatLoading.value = true
    
    // 检查是否在微信环境中
    const systemInfo = Taro.getSystemInfoSync()
    const isWechatEnv = systemInfo.platform === 'wechat' || 
                       systemInfo.platform === 'weapp' ||
                       (typeof window !== 'undefined' && /MicroMessenger/i.test(navigator.userAgent))
    
    if (!isWechatEnv) {
      Taro.showToast({
        title: '请在微信中打开',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    // 检查是否需要授权
    if (!wechatAuth.shouldAuth()) {
      Taro.showToast({
        title: '无需重新授权',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    // 执行微信授权
    await wechatAuth.authorize()
    
  } catch (error) {
    console.error('微信授权失败:', error)
    Taro.showToast({
      title: '微信授权失败，请重试',
      icon: 'none',
      duration: 2000
    })
  } finally {
    isWechatLoading.value = false
  }
}

/**
 * 检查微信授权状态
 * @description 页面加载时检查是否已有有效的微信授权
 */
const checkWechatAuthStatus = () => {
  if (wechatAuth.checkAuthStatus()) {
    console.log('检测到有效的微信授权')
    // 可以自动跳转到首页或显示已登录状态
  }
}

// 初始化
onMounted(() => {
  // 初始显示提示
  setTimeout(() => {
    showTip.value = true
  }, 1000)
  
  // 检查微信授权状态
  checkWechatAuthStatus()
})
</script>